package com.kate.mall.order.price;

import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.kate.mall.order.dto.GoodsSkuDTO;
import com.kate.mall.order.dto.OrderItemDTO;
import com.kate.mall.order.dto.PromotionActivityDTO;
import com.kate.mall.order.feign.ProductFeignClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * 满赠类型的促销胡活动的处理器
 * @author kate2chan
 *
 */
@Component
public class ReachGiftPromotionActivityCalculator 
		extends AbstractGiftPromotionActivityCalculator 
		implements PromotionActivityCalculator {

	@Resource
	private ProductFeignClient productFeignClient;
	/**
	 * 计算促销活动的减免金额
	 */
	@Override
	public PromotionActivityResult calculate(OrderItemDTO item,
											 PromotionActivityDTO promotionActivity) throws Exception {
		BigDecimal totalAmount =  item.getPrice().multiply(new BigDecimal(item.getNumber()));

		JSONObject rule = JSONUtil.parseObj (promotionActivity.getRule());

		BigDecimal thresholdAmount = rule.get("thresholdAmount",BigDecimal.class);
		JSONArray giftGoodsSkuIds = rule.getJSONArray("giftGoodsSkuIds");
		
		if(totalAmount.compareTo(thresholdAmount)==1) {
			PromotionActivityResult result = new PromotionActivityResult();
			
			for(int i = 0; i < giftGoodsSkuIds.size(); i++) {
				Integer goodsSkuId = giftGoodsSkuIds.getInt(i);
				GoodsSkuDTO goodsSku = MapUtil.get( productFeignClient.getGoodsSkuById(goodsSkuId),"goodsProduct",GoodsSkuDTO.class);
				result.getOrderItems().add(createOrderItem(goodsSku));
			} 
			
			return result;
		}
		
		return new PromotionActivityResult(); 
	}
	
}